package httpclient.processor;

import org.apache.http.client.entity.EntityBuilder;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpRequestBase;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;

public class PostProcessor extends MethodProcessor {

	@Override
	public HttpRequestBase doRequest(HttpServletRequest request) {
        if (request == null || !(request instanceof HttpServletRequest)) {
            return null;
        }

        if (!request.getMethod().equals("POST")) {
            return null;
        } 

        String queryString = "";
        if (request.getQueryString() != null) queryString += "?"+request.getQueryString();
        // 获得目标url
        String url = TARGET_URL + request.getRequestURI()+queryString;
        System.out.println(url);
        // 目标路径为空
        if (url == null || url == "") {
            return null;
        }

        // 创建POST请求
        HttpPost httpPost = new HttpPost(url);
        
        // 处理请求协议
        httpPost.setProtocolVersion(doProtocol(request));
        // 处理请求头
        httpPost.setHeaders(doHeaders(request));
        // 处理请求体
        try {
        	EntityBuilder entity = EntityBuilder.create();
        	entity.setStream(request.getInputStream());
            httpPost.setEntity(entity.build());
        } catch (IOException e) {
            // 取流失败，则要抛出异常，阻止本次请求
            throw new RuntimeException(e);
        }
        return httpPost;
    }

    @Override
	public HttpRequestBase doRequest(HttpServletRequest request, String uri) {
		if (request == null || !(request instanceof HttpServletRequest)) {
			return null;
		}
		
		if (!request.getMethod().equals("POST")) {
			return null;
		} 
		
    	String queryString = "";
    	if (request.getQueryString() != null) queryString += "?"+request.getQueryString();
    	// 获得目标url
    	String url = TARGET_URL + uri +queryString;
		System.out.println(url);
		// 目标路径为空
		if (url == null || url == "") {
			return null;
		}
		
		// 创建POST请求
		HttpPost httpPost = new HttpPost(url);
		
		// 处理请求协议
		httpPost.setProtocolVersion(doProtocol(request));
		// 处理请求头
		httpPost.setHeaders(doHeaders(request));
		// 处理请求体
		try {
			EntityBuilder entity = EntityBuilder.create();
			entity.setStream(request.getInputStream());
			httpPost.setEntity(entity.build());
		} catch (IOException e) {
			// 取流失败，则要抛出异常，阻止本次请求
			throw new RuntimeException(e);
		}
		return httpPost;
	}
}
